package handler

import (
	"strconv"

	"github.com/atcharles/wslt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"

	"gitee.com/goframe/lt-collector/libs/libgin"
	"gitee.com/goframe/lt-collector/libs/orma"
	"gitee.com/goframe/lt-collector/model"
)

var (
	ConnectorHandler WsUser
)

type (
	WsUser struct {
		*model.User

		connection *wslt.Connection
	}
)

func (w WsUser) Handle() {
	//获取当前彩种开奖信息
	model.ModeWebsocket.ReadHandle("GameNowInfo", func(c *wslt.Context) {
		lt := new(model.GameLotteries)
		w.getOpenData("NowInfo", c, lt, lt.OpenInfo)
	})
	//获取彩种最近一次开奖信息
	model.ModeWebsocket.ReadHandle("GameLatestOpenData", func(c *wslt.Context) {
		lt := new(model.GameLotteries)
		w.getOpenData("OpenData", c, lt, lt.GetLatestOpenData)
	})
}

func (WsUser) getOpenData(msgType string, c *wslt.Context, lt *model.GameLotteries, fn func() (*model.OpenData, error)) {
	var (
		err      error
		openData *model.OpenData
		ltName   string
	)
	msg, msgErr := c.BindCallRequest()
	defer func() {
		if err != nil {
			if msgErr != nil {
				_ = c.Connection.SendMessage("error", err.Error())
			} else {
				c.SendCallBackMsg(msg, err.Error())
			}
		}
	}()

	if msgErr != nil {
		if err = c.Message.UnmarshalData(&ltName); err != nil {
			return
		}
	} else {
		ltName = msg.Args["lot_name"].(string)
	}

	err = orma.NormalGet(lt.Session().Where("`name`=?", ltName).Get(lt))
	if err != nil {
		return
	}
	openData, err = fn()
	if err != nil {
		return
	}
	if msgErr != nil {
		_ = c.Connection.SendMessage(msgType, openData)
	} else {
		c.SendCallBackMsg(msg, openData)
	}
	return
}

func (WsUser) Sids() gin.HandlerFunc {
	return libgin.Return.WarpHandler(func(c *gin.Context) (err error) {
		uid, _ := strconv.Atoi(c.Param("uid"))
		libgin.Return.GinOK(c, wslt.GlobalSession().GetSidsByConnectorID(int64(uid)))
		return
	})
}

func (w *WsUser) GetID() int64 {
	if w.User == nil {
		return 0
	}
	return w.User.ID
}

func (w *WsUser) SetConnection(conn *wslt.Connection) {
	w.connection = conn
}

func (w *WsUser) Connection() *wslt.Connection {
	return w.connection
}

func (w *WsUser) NewInstance() wslt.Connector {
	return new(WsUser)
}

func (w *WsUser) CheckAuth(token string, wConn *websocket.Conn) (err error) {
	w.User = new(model.User)
	if err = w.User.AuthBySecret(token); err != nil {
		return
	}
	if w.Role != model.AuthUser && w.Role != model.AuthManager {
		return model.ErrForbidden
	}
	return
}
